#!/usr/bin/env python
#-*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
from upload_ui import Ui_Dlg_upload
from bbs_proxy_ui import Ui_Dialog_setProxy
from stuBBS import BBS


from time import sleep

import threading
import sys
import os
import httplib
import base64

isOut=True
inDomain="bbs.stu.edu.cn"
outDomain="www.bbs.stu.edu.cn"

proxy_info={}

class MY_THREAD(threading.Thread):
    def __init__(self, func, args, name = ''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args
        self.over = False

    def run(self):
        while not isOut:
            if self.over:
                sys.exit(1)
            else:
                apply(self.func, self.args)
    def kill(self):
        self.over = True

class SET_PROXY_DLG(QtGui.QDialog):
    def __init__(self, parent=None):
        super(SET_PROXY_DLG, self).__init__(parent)

        self.host = '202.104.245.178'
        self.port = '8080'
        self.account = ''
        self.password = ''

        self.test_proxy_info={}


        self.ui = Ui_Dialog_setProxy()

        self.ui.setupUi(self)
        self.ui.lineEdit_host.setText(self.host)
        self.ui.lineEdit_port.setText(self.port)
        self.ui.lineEdit_account.setFocus(QtCore.Qt.MouseFocusReason)

        QtCore.QObject.connect(self.ui.pushButton_apply, QtCore.SIGNAL("clicked()"), self.apply)
        QtCore.QObject.connect(self.ui.pushButton_cancle, QtCore.SIGNAL("clicked()"), self.cancle)
        QtCore.QObject.connect(self.ui.pushButton_test, QtCore.SIGNAL("clicked()"), self.test_proxy)
    
    def test_proxy(self):
        #self.test_proxy_inof['isProxy']=True
        self.test_proxy_info['host']= str(self.ui.lineEdit_host.text())
        self.test_proxy_info['port']= int(str(self.ui.lineEdit_port.text()))
        self.test_proxy_info['account']= str(self.ui.lineEdit_account.text())
        self.test_proxy_info['password']= str(self.ui.lineEdit_password.text())

        test_url='http://www.bbs.stu.edu.cn/main.html'
        test_headers = {'Host':'www.bbs.stu.edu.cn',
                        'User-Agent':'Mozilla/5.0 (Linux; Everest; X11; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9',
                        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                        'Accept-Language':'zh-cn,zh;q=0.5',
                        'Accept-Encoding':'gzip,deflate',
                        'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7',
                        'Keep-Alive':'300',
                        'Proxy-Connection':'keep-alive',
                        'Proxy-Authorization':'Basic %s' % base64.encodestring('%s:%s' % (self.test_proxy_info['account'], 
                            self.test_proxy_info['password']))[:-1]
                        }
        
        conn = httplib.HTTPConnection(self.test_proxy_info['host'],self.test_proxy_info['port'])

        import socket
        socket.setdefaulttimeout(3)
        try:
            conn.request("GET", test_url, headers=test_headers)
        except:
            QtGui.QMessageBox.information(None, u"验证代理", u'失败: 连接不到代理服务器!', u'确定')
            return
            
        r1 = conn.getresponse()
        print r1.status, r1.reason

        if r1.status==200:
            QtGui.QMessageBox.information(None, u"验证代理", u'成功:代理可以使用', u'确定')
            return
        if r1.status == 407:
            QtGui.QMessageBox.information(None, u"验证代理", u'失败: 用户名或密码错误', u'确定')
            return
        

    def apply(self):
        self.host = str(self.ui.lineEdit_host.text())
        self.port = str(self.ui.lineEdit_port.text())
        self.account = str(self.ui.lineEdit_account.text())
        self.password = str(self.ui.lineEdit_password.text())

        if self.host == '':
            QtGui.QMessageBox.warning(None, u'填写错误', u'代理服务器不能为空!', u'确定')
            self.ui.lineEdit_host.setFocus(QtCore.Qt.MouseFocusReason)
            return
        if self.port == '':
            QtGui.QMessageBox.warning(None, u'填写错误', u'端口号不能为空!', u'确定')
            self.ui.lineEdit_port.setFocus(QtCore.Qt.MouseFocusReason)
            return

        global proxy_info
        proxy_info['isProxy']=True
        proxy_info['host'] = self.host
        proxy_info['port'] = int(self.port)
        proxy_info['account'] = self.account
        proxy_info['password'] = self.password

        #print proxy_info
        self.accept()


    def cancle(self):
        self.reject()


class STU_UPLOAD(QtGui.QMainWindow):
    def __init__(self,parent=None):

        self.domain=''
        self.bbsid=''
        self.password=''
        self.bbs=''
        self.files=[]
        self.uploadResult=[]
        self.ok=0
        self.fail=0
        proxy_info['isProxy']=False

        QtGui.QWidget.__init__(self, parent)
        self.ui=Ui_Dlg_upload()
        self.ui.setupUi(self)
        self.ui.pushButton_upload.setEnabled(False)
        self.ui.pushButton_mj.setEnabled(False)
        self.ui.lineEdit_id.setFocus(QtCore.Qt.MouseFocusReason)

        self.centerUi()

        QtCore.QObject.connect(self.ui.pushButton_login, QtCore.SIGNAL("clicked()"), self.login_logout)
        QtCore.QObject.connect(self.ui.pushButton_upload, QtCore.SIGNAL("clicked()"), self.upload)
        QtCore.QObject.connect(self.ui.pushButton_cancle, QtCore.SIGNAL("clicked()"), self.cancle)
        QtCore.QObject.connect(self.ui.pushButton_select, QtCore.SIGNAL("clicked()"), self.getFiles)
        QtCore.QObject.connect(self.ui.pushButton_mj, QtCore.SIGNAL("clicked()"), self.hangMJ)
        QtCore.QObject.connect(self.ui.checkBox_proxy, QtCore.SIGNAL("clicked()"), self.setProxy)

    def setProxy(self):
        if self.ui.checkBox_proxy.isChecked():
            set_proxy_dlg = SET_PROXY_DLG()
            if set_proxy_dlg.exec_():
                pass
                #print proxy_info
        else:
            #global proxy_info
            proxy_info['isProxy']=False

    def centerUi(self):
        screen = QtGui.QDesktopWidget().screenGeometry() #获取显示器分辨率
        size = self.geometry() #获得窗体大小
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

    def login_logout(self):
        print proxy_info
        self.bbsid = str(self.ui.lineEdit_id.text()).lower()
        self.password = str(self.ui.lineEdit_password.text())
        if self.bbsid=='':
            QtGui.QMessageBox.warning(None, u'请输入帐号', u"帐号不能为空，请输入帐号", u"确定")
            self.ui.lineEdit_id.setFocus(QtCore.Qt.MouseFocusReason)
            return
        if self.password == '':
            QtGui.QMessageBox.warning(None, u'请输入密码', u"密码不能为空，请输入密码", u"确定")
            self.ui.lineEdit_password.setFocus(QtCore.Qt.MouseFocusReason)
            return

        if self.ui.radioButton_in.isChecked():
            self.domain=inDomain
            #print self.domain
        else:
            self.domain=outDomain
            #print self.domain

        global isOut
        print isOut
        if isOut:
            self.bbs = BBS(self.domain, self.bbsid, self.password, debug=False, proxy_info=proxy_info)
            islogin = self.bbs.login()
            if not islogin:
                QtGui.QMessageBox.warning(None, u'错误', u'请检查帐号和密码的是否正确', u'确定')
                self.ui.lineEdit_id.setFocus(QtCore.Qt.MouseFocusReason)
                return
            else:
                isOut=False
                self.ui.textBrowser.append(u"登录->>>>>>>>>>>>>><font color='blue'>成功!</font>")
                self.ui.pushButton_login.setText(u'注销')
                self.ui.pushButton_upload.setEnabled(True)
                self.ui.pushButton_mj.setEnabled(True)
                self.ui.lineEdit_id.setEnabled(False)
                self.ui.lineEdit_password.setEnabled(False)
                self.ui.checkBox_proxy.setEnabled(False)
                self.ui.radioButton_in.setEnabled(False)
                self.ui.radioButton_out.setEnabled(False)

                global t_keep
                t_keep = MY_THREAD(self.keepAlive, ())

        else:
            self.logout()
            #isOut=True
            #t_keep.kill()

    def logout(self):
        self.bbs.logout()
        global isOut
        global t_keep
        isOut=True
        t_keep.kill()
        self.ui.textBrowser.append(u"注销->>>>>>>>>>>>>><font color='blue'>成功!</font>")
        self.ui.pushButton_login.setText(u'登录')
        self.ui.pushButton_upload.setEnabled(False)
        self.ui.pushButton_mj.setEnabled(False)
        self.ui.lineEdit_id.setEnabled(True)
        self.ui.lineEdit_password.setEnabled(True)
        self.ui.checkBox_proxy.setEnabled(True)
        self.ui.radioButton_in.setEnabled(True)
        self.ui.radioButton_out.setEnabled(True)

    def upload(self):
        for pic in self.files:
            isUpload = self.bbs.uploadPicture(pic)
            if isUpload:
                self.ui.textBrowser.append(u"%s 上传<font color='blue'>成功</font>"% QtCore.QString.fromLocal8Bit(pic))
                #print "%s upload.....OK!"% pic
                self.ok=self.ok+1
            else:
                self.ui.textBrowser.append(u"%s 上传<font color='red'>失败</font>"% QtCore.QString.fromLocal8Bit(pic))
                #print "%s upload.....Fail!"% pic
                self.fail=self.fail+1
        QtGui.QMessageBox.information(None, u"上传完毕", u"上传成功%s张，失败%s张"% (self.ok, self.fail), u"确定")
        self.ui.textBrowser.append(u"==========上传成功:<font color='blue'>&nbsp;%s&nbsp;</font>张,失败:<font color='red'>&nbsp;%s&nbsp;</font>张!========="% (QtCore.QString.fromLocal8Bit(str(self.ok)), QtCore.QString.fromLocal8Bit(str(self.fail))))
        self.ok=0
        self.fail=0


    def cancle(self):
        self.ui.textBrowser.clear()
        sys.exit(1)


    def getFiles(self):
        self.ui.textBrowser.clear()
        self.files=[]
        fileDlg = QtGui.QFileDialog()
        fileList = fileDlg.getOpenFileNames(self, 
                u"请选择您需要上传的图片，可以按着CTRL键选择多个", 
                os.path.expanduser("~/"),
                "Images (*.png *.xpm *.jpg)")
        for file in fileList:
            #print str(file.toLocal8Bit())
            fileSize = os.path.getsize(str(file.toLocal8Bit()))
            if fileSize > 524288:
                QtGui.QMessageBox.warning(None, 
                        u'图片大于512K', 
                        u'图片%s大于512K，程序将取消该图片上传'% os.path.split(str(file.toLocal8Bit()))[1], 
                        u'确定')
            else:
                self.files.append(str(file.toLocal8Bit()))
                self.ui.textBrowser.append(file)

        self.ui.textBrowser.append(u"==========共<font color='blue'>&nbsp;%s&nbsp;</font>张图片========="% QtCore.QString.fromLocal8Bit(str(len(self.files))))

    def keepAlive(self, sleeptime=300):

        header, page = self.bbs.getFoot()
        if -1 != page.lower().find(self.bbsid):
            sleep(sleeptime) #5 min= 300s
            print "Online!"
        else:
            self.ui.textBrowser.append(u"注意：->>>>>>>>>>>>>><font color='red'>离线了</font>")
            self.logout()
            #return False


    def hangMJ(self):
        t_keep.setDaemon(True)
        t_keep.start()
        self.ui.pushButton_mj.setEnabled(False)
        self.ui.textBrowser.append(u"晒马甲->>>>>>>>>>>>>><font color='blue'>成功!</font>")



if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    stu_upload = STU_UPLOAD()
    stu_upload.show()
    sys.exit(app.exec_())


